#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int count = 0;
void *start_routine1(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (count % 2 == 0)
            pthread_cond_wait(&cond, &mutex);
        cout << "我是线程A" << endl;
        ++count;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

void *start_routine2(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (count % 2 == 1)
            pthread_cond_wait(&cond, &mutex);
        cout << "我是线程B" << endl;
        ++count;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}
int main()
{
    pthread_t t1, t2;
    pthread_create(&t1, nullptr, start_routine1, nullptr);
    pthread_create(&t2, nullptr, start_routine2, nullptr);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    return 0;
}